<template>
  <div ref="boxwrap" :class="['ParamsStatus', {visiable: circleShow}]">
    <div :id="id" class="paramsChart chart" :width="chartStyle.width" :height="chartStyle.height" />
    <div v-show="tooltipShow" class="tooltipText">
      <div>达标</div>
      <div>{{ value.rate }}%</div>
    </div>
  </div>
</template>

<script>
import resize from '@/components/Charts/mixins/resize'
import { getParamsStatus } from '@/api/screen'
export default ({
  name: 'ParamsStatus',
  mixins: [resize],
  props: {
    width: {
      type: String,
      default: '150px'
    },
    height: {
      type: String,
      default: '150px'
    },
    isresize: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      list: [],
      id: 'ParamsStatus',
      chart: null,
      option: {},
      color: ['#ff8c00', '#7131a1', '#0071c1', '#00af50', '#ffff00'],
      fontColor: ['#bebebe', '#ff0000'],
      scrollTimer: null, // 轮播定时器
      interval: 3000, // 轮播速度
      isCircle: false,
      chartStyle: {
        width: '100%',
        height: '100%'
      },
      tooltipShow: false,
      circleShow: false,
      value: {},
      resData: [],
      currentView: {},
      typeObj: { 1: '温度', 2: '压力', 3: '流量', 5: '线速' },
      refreshTimer: null, // 数据刷新定时器
      refreshInterval: 1000 * 60
    }
  },
  // computed: {
  //   ...mapGetters([
  //     'regionid',
  //     'lineId'
  //   ])
  // },
  watch: {
    width: {
      immediate: true,
      handler: function(newval, oldval) {
        this.width = newval
      },
      deep: true
    },
    height: {
      immediate: true,
      handler: function(newval, oldval) {
        this.height = newval
      },
      deep: true
    }
  },
  mounted() {
    this.getDomHeight()
    this.domResize()
    // this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    if (this.scrollTimer) {
      clearTimeout(this.scrollTimer)
      this.scrollTimer = null
    }
    this.chart.dispose()
    this.chart = null
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer)
      this.refreshTimer = null
    }
  },
  created() {
    this.getCurrentView()
    if (this.$route.path.indexOf('/screen') !== -1) {
      this.dataRefresh()
    }
  },
  methods: {
    getDomHeight() {
      this.chartStyle = {
        width: this.$refs.boxwrap.clientWidth + 'px',
        height: this.$refs.boxwrap.clientHeight + 'px'
      }
    },
    getCurrentView() {
      this.currentView = {
        regionid: this.$Cookies.get('currentReginid'),
        lineId: this.$Cookies.get('currentLineId')
      }
      this.getData()
    },
    getData() {
      getParamsStatus(this.currentView).then(response => {
        this.resData = response.data

        // 浓度 数量 = 8.碳酸钠 + 9.氢氧化钠 + 10.比重 + 11.氯酸钠 + 12.盐酸
        const list = []
        const density = [] // 浓度
        let totalCount = 0
        for (let i = 0; i < this.resData.length; i++) {
          totalCount += this.resData[i].total
          if (this.resData[i].type === 8 || this.resData[i].type === 9 || this.resData[i].type === 10 || this.resData[i].type === 11 || this.resData[i].type === 12) {
            density.push(this.resData[i])
          } else {
            list.push({
              name: this.typeObj[this.resData[i].type],
              abnormal: this.resData[i].typeCount, // 异常个数
              normal: this.resData[i].total - this.resData[i].typeCount,
              total: this.resData[i].total // 总数
            })
          }
        }
        if (density.length > 0) {
          const densityabnormal = []
          const densitytotal = []
          for (let i = 0; i < density.length; i++) {
            densityabnormal.push(density[i].typeCount)
            densitytotal.push(density[i].total)
          }
          const abnormal = this.sumArray(densityabnormal)
          const total = this.sumArray(densitytotal)
          list.push({
            name: '浓度',
            abnormal: abnormal,
            normal: total - abnormal,
            total: total // 总数
          })
        } else {
          list.push({
            name: '浓度',
            abnormal: 0,
            normal: 0,
            total: 0 // 总数
          })
        }

        const dataArr = []
        for (let i = 0; i < list.length; i++) {
          let rate = 0
          if (list[i].normal !== 0 && list[i].total !== 0) {
            rate = (list[i].normal / list[i].total * 100).toFixed(1)
          }
          dataArr.push({
            name: list[i].name,
            value: 1,
            normal: list[i].normal,
            abnormal: list[i].abnormal,
            total: list[i].total,
            rate: rate,
            itemStyle: {
              color: list[i].abnormal > 0 ? this.fontColor[1] : this.color[i],
              borderRadius: 10,
              shadowColor: list[i].abnormal > 0 ? this.fontColor[1] : this.color[i],
              shadowBlur: 5
            },
            label: {
              color: list[i].abnormal > 0 ? this.fontColor[1] : this.fontColor[0]
            },
            emphasis: {
              label: {
                color: list[i].abnormal > 0 ? this.fontColor[1] : '#fff'
              }
            }
          })
        }
        this.initChart(dataArr, totalCount)
      })
    },
    // 数组求和
    sumArray(array) {
      var sum = 0
      array.forEach(function(val, index, array) {
        sum += val
      })
      return sum
    },
    showtoolTip(val) {
      this.tooltipShow = true
      this.value = val
    },
    showCircles(val) {
      this.circleShow = val
    },
    domResize() {
      const that = this
      const dom = this.$refs.boxwrap
      this.$erd.listenTo(dom, function(element) {
        var width = element.clientWidth + 'px'
        var height = element.clientHeight + 'px'
        that.chartStyle = {
          width,
          height
        }
      })
    },
    initChart(dataArr, totalCount) {
      const that = this
      this.chart = this.$echarts.init(document.getElementById(this.id), 'jyt-dark')
      this.option = {
        title: {
          text: '合计:' + totalCount + '台',
          textStyle: {
            color: '#fff',
            fontSize: 16
          },
          right: 0,
          bottom: 0
        },
        tooltip: {
          show: false,
          trigger: 'item',
          backgroundColor: 'transparent',
          borderWidth: 0,
          textStyle: {
            color: 'cyan'
          },
          formatter: function(params) {
            that.showtoolTip(params.data)
          }
        },
        series: [
          {
            // 数据环
            type: 'pie',
            zlevel: 4,
            radius: ['66%', '76%'],
            color: this.color,
            startAngle: 180,
            itemStyle: {
              borderRadius: 10,
              shadowBlur: 5
            },
            label: {
              show: true,
              position: 'outside',
              color: '#bebebe',
              lineHeight: 20,
              textAlign: 'left',
              formatter: function(params) {
                const str = params.name + '\n' + params.data.total + '台(' + params.data.abnormal + ')'
                return params.name === '' ? '' : str
              }
            },
            labelLine: {
              length: 10,
              length2: 30,
              show: true,
              color: '#00ffff'
            },
            emphasis: {
              scale: true,
              scaleSize: 8,
              label: {
                show: true,
                // fontSize: '14',
                fontWeight: 'bold',
                color: '#fff'
              }
            },
            data: dataArr
          },
          {
            // 装饰环 - 内
            type: 'pie',
            zlevel: 2,
            silent: true,
            radius: ['56%', '60%'],
            startAngle: 90,
            label: {
              show: false
            },
            labelLine: {
              show: false
            },
            data: this.innerCircleData()
          }
        ]
      }
      this.chart.setOption(this.option)
      this.showCircles(true)
      this.autoTooltip(dataArr, this.chart, this.option, this)
    },
    innerCircleData() {
      const dataArr = []
      for (var i = 0; i < 8; i++) {
        if (i % 2 === 1) {
          dataArr.push({
            value: 20,
            itemStyle: {
              borderRadius: 10,
              color: 'yellow'
            }
          })
        } else {
          dataArr.push({
            value: 4,
            itemStyle: {
              borderRadius: 10,
              color: 'rgba(0,0,0,0)'
            }
          })
        }
      }
      return dataArr
    },
    // 自动轮播 Tooltip
    autoTooltip(dataArr, myChart, option, that) {
      // 参数为2个及以上，开始轮播
      this.scrollTimer = null
      if (dataArr.length > 1) {
        var currentIndex = -1
        if (this.scrollTimer) {
          clearTimeout(this.scrollTimer)
        }
        this.scrollTimer = setInterval(function() {
          var dataLen = option.series[0].data.length
          // 取消之前高亮的图形
          myChart.dispatchAction({
            type: 'downplay',
            seriesIndex: 0,
            dataIndex: currentIndex
          })
          currentIndex = (currentIndex + 1) % dataLen
          // 高亮当前图形
          myChart.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex: currentIndex
          })
          // 显示 tooltip
          that.showtoolTip(dataArr[currentIndex])
          // myChart.dispatchAction({
          //   type: 'showTip',
          //   seriesIndex: 0,
          //   dataIndex: currentIndex
          // })
        }, this.interval)
      } else {
        myChart.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: 0
        })
      }
    },
    // 数据刷新
    dataRefresh() {
      if (this.refreshTimer) {
        clearTimeout(this.refreshTimer)
        this.refreshTimer = null
      }
      if (this.chart) {
        this.chart.dispose()
        this.chart = null
      }
      if (this.scrollTimer) {
        clearTimeout(this.scrollTimer)
        this.scrollTimer = null
      }
      this.refreshTimer = setTimeout(() => {
        this.getData()
        this.dataRefresh()
      }, this.refreshInterval)
    }
  }
})
</script>

<style lang="scss">
$bgiUrl: '../../../assets/public_images/';
$circleRotate: circleRotate 6s linear infinite;
@keyframes circleRotate{
    0% {
        transform:translate(-50%, -50%) rotateZ(0deg);
    }
    100% {
        transform:translate(-50%, -50%) rotateZ(360deg);
    }
}

.ParamsStatus{
  position: relative;

  .chart{
    width: 100%;
    height: 100%;
  }

  &.visiable::after{
     content: '';
    width: 40%;
    height: 60%;
    position: absolute;
    top: 50%;
    left: 50%;
    z-index: -1;
    visibility: true;
    transform: translate(-50%, -50%);
    background: url($bgiUrl + "c2.png") no-repeat;
    background-size: contain;
    background-position: 50%;
    animation: $circleRotate
  }

  .tooltipText{
    color: '#bebebe';
    text-align: center;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50% , -50%);
  }
}
</style>
